package app

import (
	"fmt"
	"html/template"
	"log"
	"net/http"
	"time"
//	"strings"
)

//菜单管理首页
func (G *Global) SysMenu(w http.ResponseWriter, r *http.Request) {

//	a, Err := G.SelectOne("SELECT * FROM salt_template")
//	fmt.Println(Err)
//	c := a["txt"]

//	fmt.Println(strings.Replace(strings.Replace(strings.Replace(strings.Replace(c, "TheRemotePath", "/data/", 2), "TheLocalPath", "/data/web", 2), "User", "root", 2), "Group", "root", 2))

	t, template_err := template.ParseFiles("templates/sys/menu.html", "templates/common/head.html", "templates/common/foot.html")
	if template_err != nil {
		log.Println(template_err.Error())
		fmt.Fprintf(w, template_err.Error())
	} else {
		t.Execute(w, G)
	}
}

//添加菜单
func (G *Global) SysMenuAdd(w http.ResponseWriter, r *http.Request) {
	if r.Method == "GET" {
		http.Redirect(w, r, "/sys/menu", http.StatusFound)
	}
	if r.Method == "POST" {
		MenuGrade := r.PostFormValue("menu_grade")            //菜单级别
		MenuName := r.PostFormValue("menu_name")              //菜单名称
		MenuUrl := r.PostFormValue("menu_url")                //菜单地址
		MenuSuperiorId := r.PostFormValue("superior_menu_id") //上级菜单ID

		G.Info = make(map[string]string)
		G.Info["url"] = "/sys/menu"

		if MenuGrade != "1" { // 不是一级菜单就有菜单地址

			if UrlInfo, Err := G.SelectOne("SELECT menu_url FROM menu where menu_url = ?", MenuUrl); Err == nil {
				if UrlInfo["menu_url"] == MenuUrl {
					fmt.Fprint(w, Get_Json("菜单地址重复!"))
					return
				}
			} else {
				log.Println(Err.Error())
				fmt.Fprint(w, Get_Json("添加失败!"))
				return
			}
		}
		_, Err := G.Insert("INSERT INTO menu (menu_name, menu_grade, superior_menu, instruction,create_time,menu_url) VALUES (?,?,?,?,?,?)", MenuName, MenuGrade, MenuSuperiorId, "", time.Now().Format("2006-01-02 15:04:05"), MenuUrl)

		if Err == nil {
			fmt.Fprint(w, Get_Json("Success"))
		} else {
			fmt.Fprint(w, Get_Json("添加失败!"))
			http.Redirect(w, r, "/error", http.StatusFound)
		}
	}
}

//删除菜单
func (G *Global) SysMenuDel(w http.ResponseWriter, r *http.Request) {
	if r.Method == "POST" {
		if _, Err := G.Delete("DELETE FROM menu WHERE id=?", r.PostFormValue("id")); Err == nil {
			fmt.Fprint(w, Get_Json("Success"))
		} else {
			log.Println(Err.Error())
			fmt.Fprint(w, Get_Json("删除失败!"))
		}
	}
}

//用户管理首页
func (G *Global) SysUser(w http.ResponseWriter, r *http.Request) {
	if UserAll, Err := G.SelectAll("SELECT id,user_name,role_id,status,login_time,create_time FROM users"); Err == nil {
		if RoleAll, Err := G.SelectAll("SELECT id,role_name,create_time FROM roles"); Err == nil {
			out := map[string]interface{}{"Global": G, "UserAll": UserAll, "RoleAll": RoleAll}
			t, template_err := template.ParseFiles("templates/sys/user.html", "templates/common/head.html", "templates/common/foot.html")
			if template_err != nil {
				log.Println(template_err.Error())
				fmt.Fprintf(w, template_err.Error())
			} else {
				t.Execute(w, out)
			}
		} else {
			fmt.Println(Err.Error())
		}
	} else {
		fmt.Println(Err.Error())
	}
}

//添加用户
func (G *Global) SysUserAdd(w http.ResponseWriter, r *http.Request) {
	if r.Method == "GET" {
		http.Redirect(w, r, "/sys/user", http.StatusFound)
	}
	if r.Method == "POST" {
		UserName := r.PostFormValue("username")  //用户名
		RoleId := r.PostFormValue("role_id")     //角色
		Passworsd := r.PostFormValue("password") //密码

		G.Info = make(map[string]string)
		G.Info["url"] = "/sys/user"

		if UrlInfo, Err := G.SelectOne("SELECT user_name FROM users where user_name = ?", UserName); Err == nil {
			if UrlInfo["user_name"] == UserName {
				fmt.Fprint(w, Get_Json("用户名重复!"))
				return
			}
		} else {
			log.Println(Err.Error())
			fmt.Fprint(w, Get_Json("添加失败!"))
			return
		}

		_, Err := G.Insert("INSERT INTO users (user_name, passwd,role_id,create_time) VALUES (?, ?,?, ?)", UserName, G.UserInfo.PasswdMD5(Passworsd), RoleId, time.Now().Format("2006-01-02 15:04:05"))
		if Err == nil {
			fmt.Fprint(w, Get_Json("Success"))
		} else {
			log.Println("添加失败：", Err.Error())
			fmt.Fprint(w, Get_Json("添加失败!"))

		}
	}
}

//删除用户
func (G *Global) SysUserDel(w http.ResponseWriter, r *http.Request) {
	if r.Method == "POST" {
		if _, Err := G.Delete("DELETE FROM users where id=?", r.PostFormValue("id")); Err == nil {
			fmt.Fprint(w, Get_Json("Success"))
		} else {
			log.Println(Err.Error())
			fmt.Fprint(w, Get_Json("删除失败!"))
		}
	}
}

//用户编辑
func (G *Global) SysUserEDit(w http.ResponseWriter, r *http.Request) {
	if r.Method == "POST" {
		G.Info = make(map[string]string)

		switch r.PostFormValue("operation") {

		case "status":
			G.Info["SQL"] = fmt.Sprintf("UPDATE users set %s =%s WHERE id =%s", r.PostFormValue("operation"), r.PostFormValue("status"), r.PostFormValue("id"))

		case "role_id":
			G.Info["SQL"] = fmt.Sprintf("UPDATE users set %s =%s WHERE id =%s", r.PostFormValue("operation"), r.PostFormValue("role_id"), r.PostFormValue("id"))

		case "passwd":
			G.Info["SQL"] = fmt.Sprintf("UPDATE users set %s = '%s' WHERE id =%s", r.PostFormValue("operation"), G.UserInfo.PasswdMD5(r.PostFormValue("passwd")), r.PostFormValue("id"))
		}

		if _, Err := G.Update(G.Info["SQL"]); Err == nil {
			fmt.Fprint(w, Get_Json("Success"))
		} else {
			log.Println(Err.Error())
			fmt.Fprint(w, Get_Json("编辑失败!"))
		}
	}
}

//角色管理首页
func (G *Global) SysRole(w http.ResponseWriter, r *http.Request) {

	if RoleAll, Err := G.SelectAll("SELECT id,role_name,create_time FROM roles"); Err == nil {

		out := map[string]interface{}{"Global": G, "RoleAll": RoleAll}
		t, template_err := template.ParseFiles("templates/sys/role.html", "templates/common/head.html", "templates/common/foot.html")
		if template_err != nil {
			log.Println(template_err.Error())
			fmt.Fprintf(w, template_err.Error())
		} else {
			t.Execute(w, out)
		}
	} else {
		fmt.Println(Err.Error())
	}
}

//添加角色
func (G *Global) SysRoleAdd(w http.ResponseWriter, r *http.Request) {
	if r.Method == "GET" {
		http.Redirect(w, r, "/sys/role", http.StatusFound)
	}
	if r.Method == "POST" {
		RoleName := r.PostFormValue("role_name") //角色名称
		G.Info = make(map[string]string)
		G.Info["url"] = "/sys/role"
		if UrlInfo, Err := G.SelectOne("SELECT role_name FROM roles where role_name = ?", RoleName); Err == nil {
			if UrlInfo["role_name"] == RoleName {
				fmt.Fprint(w, Get_Json("角色名称重复"))
				return
			}
		} else {
			fmt.Println(Err.Error())
			fmt.Fprint(w, Get_Json("添加失败!"))
			return
		}
		_, Err := G.Insert("INSERT INTO roles (role_name, create_time) VALUES (?, ?)", RoleName, time.Now().Format("2006-01-02 15:04:05"))
		if Err == nil {
			fmt.Fprint(w, Get_Json("Success"))
		} else {
			fmt.Fprint(w, Get_Json("添加失败!"))
			log.Println("添加失败：", Err.Error())
		}
	}
}

//删除角色
func (G *Global) SysRoleDel(w http.ResponseWriter, r *http.Request) {
	if r.Method == "POST" {
		if UserInfo, Err := G.SelectOne("SELECT id FROM users WHERE role_id =?", r.PostFormValue("id")); Err == nil {
			if UserInfo["id"] == "" {
				if _, Err := G.Delete("DELETE FROM roles where id=?", r.PostFormValue("id")); Err == nil {
					fmt.Fprint(w, Get_Json("Success"))
				} else {
					log.Println("删除失败：", Err.Error())
					fmt.Fprint(w, Get_Json("删除失败!"))
				}
			} else {
				fmt.Fprint(w, Get_Json("删除失败,该角色下面存在用户!"))
			}

		} else {
			log.Println("删除失败：", Err.Error())
			fmt.Fprint(w, Get_Json("删除失败!"))
		}

	}
}

//权限管理首页
func (G *Global) SysPerms(w http.ResponseWriter, r *http.Request) {
	if PremsAll, Err := G.SelectAll("SELECT id,role_id,menu_id  FROM permissions"); Err == nil {
		if RoleAll, Err := G.SelectAll("SELECT id,role_name,create_time FROM roles"); Err == nil {
			out := map[string]interface{}{"Global": G, "PremsAll": PremsAll, "RoleAll": RoleAll}
			t, template_err := template.ParseFiles("templates/sys/prems.html", "templates/common/head.html", "templates/common/foot.html")
			if template_err != nil {
				log.Println(template_err.Error())
				fmt.Fprintf(w, template_err.Error())
			} else {
				t.Execute(w, out)
			}
		} else {
			fmt.Println(Err.Error())
		}
	} else {
		fmt.Println(Err.Error())
	}
}

//添加权限
func (G *Global) SysPermsAdd(w http.ResponseWriter, r *http.Request) {
	if r.Method == "GET" {
		http.Redirect(w, r, "/sys/perms", http.StatusFound)
	}
	if r.Method == "POST" {
		RoleId := r.PostFormValue("role_id") //角色ID
		MenuId := r.PostFormValue("menu_id") //菜单ID
		if PremsInfo, Err := G.SelectOne("SELECT menu_id FROM permissions where menu_id = ? and role_id =?", MenuId, RoleId); Err == nil {
			if PremsInfo["menu_id"] == MenuId {
				fmt.Fprint(w, Get_Json("请勿重复添加!"))
			} else {
				if _, Err := G.Insert("INSERT INTO permissions (menu_id, role_id, permissions) VALUES (?,?,?)", MenuId, RoleId, 0); Err == nil {
					fmt.Fprint(w, Get_Json("Success"))
				} else {
					log.Println(Err.Error())
					fmt.Fprint(w, Get_Json("添加失败!"))
				}
			}
		} else {
			log.Println(Err.Error())
			fmt.Fprint(w, Get_Json("系统错误!"))
		}
	}
}

//删除权限
func (G *Global) SysPermsDel(w http.ResponseWriter, r *http.Request) {
	if r.Method == "POST" {
		if _, Err := G.Delete("DELETE FROM permissions where id=?", r.PostFormValue("id")); Err == nil {
			fmt.Fprint(w, Get_Json("删除成功!"))
		} else {
			log.Println("删除失败：", Err.Error())
			fmt.Fprint(w, Get_Json("删除失败!"))
		}
	}
}

//VPN列表管理首页
func (G *Global) SysVpnList(w http.ResponseWriter, r *http.Request) {

	if VpnListAll, Err := G.SelectAll("SELECT id,vpn_name,vpn_labelling,create_time FROM vpn_list"); Err == nil {

		out := map[string]interface{}{"Global": G, "VpnListAll": VpnListAll}
		t, template_err := template.ParseFiles("templates/sys/vpn_list.html", "templates/common/head.html", "templates/common/foot.html")
		if template_err != nil {
			log.Println(template_err.Error())
			fmt.Fprintf(w, template_err.Error())
		} else {
			t.Execute(w, out)
		}
	} else {
		fmt.Println("***********", Err.Error())
	}
}

//添加VPN信息
func (G *Global) SysVpnListAdd(w http.ResponseWriter, r *http.Request) {
	if r.Method == "GET" {
		http.Redirect(w, r, "/sys/vpn_list", http.StatusFound)
	}
	if r.Method == "POST" {
		VpnName := r.PostFormValue("vpn_name")
		VpnLabelling := r.PostFormValue("vpn_labelling")
		G.Info = make(map[string]string)
		G.Info["url"] = "/sys/role"
		if VpnInfo, Err := G.SelectOne("SELECT vpn_labelling,vpn_name FROM vpn_list where vpn_name = ? or vpn_labelling =? ", VpnName, VpnLabelling); Err == nil {
			if VpnInfo["vpn_name"] == VpnName {
				fmt.Fprint(w, Get_Json("VPN名称重复!"))
				return
			}
			if VpnInfo["vpn_labelling"] == VpnLabelling {
				fmt.Fprint(w, Get_Json("VPN标签重复!"))
				return
			}
		} else {
			fmt.Println(Err.Error())
			fmt.Fprint(w, Get_Json("系统错误!"))
			return
		}
		_, Err := G.Insert("INSERT INTO vpn_list (vpn_name, vpn_labelling,create_time) VALUES (?, ?,?)", VpnName, VpnLabelling, time.Now().Format("2006-01-02 15:04:05"))
		if Err == nil {
			fmt.Fprint(w, Get_Json("Success"))
		} else {
			fmt.Fprint(w, Get_Json("添加失败!"))
			log.Println(Err.Error())
		}
	}
}

//删除VPN信息
func (G *Global) SysVpnListDel(w http.ResponseWriter, r *http.Request) {
	if r.Method == "POST" {
		if _, Err := G.Delete("DELETE FROM vpn_list where id=?", r.PostFormValue("id")); Err == nil {
			fmt.Fprint(w, Get_Json("Success"))
		} else {
			log.Println("删除失败：", Err.Error())
			fmt.Fprint(w, Get_Json("删除失败!"))
		}
	}
}
